package com.cws.utils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cws.dto.Condition;
import com.cws.dto.PageReq;
import com.cws.enmu.RspCode;
import com.cws.enmu.RspMapKey;
import com.cws.frame.exception.CWSException;
import com.cws.sys.Constant;

public final class WSUtil {

	private static final Logger log = LoggerFactory.getLogger(WSUtil.class);

	/**
	 * 生成UUID
	 * 
	 * @return
	 */
	public static String getUUID() {
		return UUID.randomUUID().toString().replaceAll("-", "").toLowerCase();
	}

	/**
	 * 生成ws接口返回对象
	 * @param rspCode
	 * @param obj
	 * @return
	 */
	public static Map<String, Object> createRsp(RspCode rspCode, Object obj) {

		Map<String, Object> rsp = new HashMap<String, Object>();

		rsp.put(RspMapKey.CODE.name(), rspCode.getCode());
		rsp.put(RspMapKey.MSG.name(), rspCode.getDescription());
		if (null != obj) {
			rsp.put(RspMapKey.RESULT.name(), obj);
		} else {
			rsp.put(RspMapKey.RESULT.name(), "");
		}

		return rsp;
	}

	/**
	 * 生成查询语句sql
	 * @param baseSql
	 * @param req
	 * @return
	 */
	public static String GenQuerySql(String baseSql, PageReq req) {
		String sql = baseSql;

		StringBuffer sb = new StringBuffer();

		for (Condition c : req.getConditions()) {
			String filed = c.getField();
			String op = c.getOperator();
			Object value = c.getValue();

			//拼接条件
			if (value instanceof java.lang.String) {
				if (Constant.LK.equals(op.trim())) {
					sb.append(" and " + filed + " " + op + " '%" + String.valueOf(value) + "%'");
				} else {
					sb.append(" and " + filed + " " + op + " '" + String.valueOf(value) + "'");
				}
			} else if (value instanceof java.lang.Integer) {
				sb.append(" and " + filed + " " + op + " " + ((Integer) value).intValue());
			} else if (value instanceof java.lang.Double) {
				sb.append(" and " + filed + " " + op + " " + ((Double) value).doubleValue());
			} else {
				log.error("query condition value type not support.");
				throw new CWSException(RspCode.PARAMERTER_ERROR);
			}
		}

		//拼接自定义sql条件
		if (null != req.getCostomSql() && !req.getCostomSql().isEmpty()) {
			sb.append(" " + req.getCostomSql());
		}

		sql = sql + sb.toString();

		return sql;
	}
}
